<template>
  <div class="user-management-container">
    <!-- 操作区域卡片 -->
    <el-card class="operation-card" shadow="hover">
      <div class="operation-area">
        <el-button type="primary" @click="showAddModal" class="action-button">
          <i class="el-icon-plus"></i> 新增仓库
        </el-button>

        <!-- 搜索区域 -->
        <div class="search-area">
          <el-input
              placeholder="仓库编号"
              v-model="searchWareNumber"
              clearable
              prefix-icon="el-icon-user"
              class="search-input"
          ></el-input>

          <el-input
              placeholder="仓库名称"
              v-model="searchName"
              clearable
              prefix-icon="el-icon-edit"
              class="search-input"
          ></el-input>

          <el-select
              v-model="searchState"
              placeholder="仓库状态"
              clearable
              class="search-select"
          >
            <el-option label="空闲" value="空闲"></el-option>
            <el-option label="使用中" value="使用中"></el-option>
          </el-select>

          <el-input
              placeholder="仓库位置"
              v-model="searchLocation"
              clearable
              prefix-icon="el-icon-location"
              class="search-input"
          ></el-input>

          <el-select
              v-model="searchWareType"
              placeholder="仓库类型"
              clearable
              class="search-select"
          >
            <el-option label="冷冻仓库" value="冷冻仓库"></el-option>
            <el-option label="常温仓库" value="常温仓库"></el-option>
            <el-option label="化学仓库" value="化学仓库"></el-option>
            <el-option label="冷藏仓库" value="冷藏仓库"></el-option>
            <el-option label="恒温仓库" value="恒温仓库"></el-option>
          </el-select>

          <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleSearch"
              class="search-button"
          >
            搜索
          </el-button>
          <!-- 新增的重置按钮 -->
          <el-button
              type="info"
              icon="el-icon-refresh"
              @click="handleReset"
              class="search-button"
          >
            重置
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="data-card" shadow="hover">
      <el-table
          :data="tableData"
          style="width: 100%"
          v-loading="loading"
          class="data-table"
          :header-cell-style="{background: '#f5f7fa', color: '#606266'}"
      >
        <el-table-column
            type="index"
            label="序号"
            width="60"
            align="center"
            :index="calculateIndex"
        ></el-table-column>

        <el-table-column
            prop="number"
            label="仓库编号"
            width="130"
            align="center"
        ></el-table-column>

        <el-table-column
            prop="name"
            label="仓库名称"
            width="120"
            align="center"
        ></el-table-column>

        <el-table-column
            prop="state"
            label="仓库状态"
            width="80"
            align="center"
        ></el-table-column>

        <el-table-column
            prop="location"
            label="仓库位置"
            width="200"
            align="center"
        ></el-table-column>
        <el-table-column
            prop="type"
            label="仓库类型"
            width="120"
            align="center"
        ></el-table-column>
        <el-table-column
            prop="area"
            label="仓库面积(平方米)"
            width="120"
            align="center"
        ></el-table-column>
        <el-table-column
            label="操作"
            width="500"
            align="center"
            fixed="right"
        >
          <template v-slot="scope">
            <el-button
                @click="handleEdit(scope.row)"
                type="primary"
                size="mini"
                class="action-button"
            >
              <i class="el-icon-edit"></i> 修改
            </el-button>
            <el-button
                type="danger"
                @click="handleDelete(scope.row)"
                size="mini"
                class="action-button"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
            <el-button
                type="primary"
                @click="handleViewArea(scope.row)"
                size="mini"
                class="action-button"
            >
              <i class="el-icon-view"></i> 查看区域详情
            </el-button>
            <el-button
                type="primary"
                @click="handleViewGoods(scope.row)"
                size="mini"
                class="action-button"
            >
              <i class="el-icon-view"></i> 查看货物详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pageSize"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 新增仓库模态框 -->
    <el-dialog
        title="新增仓库"
        :visible.sync="addDialogVisible"
        width="500px"
        :close-on-click-modal="false"
    >
      <el-form
          :model="addForm"
          :rules="rules"
          ref="addForm"
          label-width="100px"
      >
        <el-form-item label="仓库名称" prop="name">
          <el-input
              v-model="addForm.name"
              placeholder="请输入仓库名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="仓库状态" prop="state">
          <el-select
              v-model="addForm.state"
              placeholder="请选择仓库状态"
          >
            <el-option label="空闲" value="空闲"></el-option>
            <el-option label="使用中" value="使用中"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库位置" prop="location">
          <el-input
              v-model="addForm.location"
              placeholder="请输入仓库位置"
          ></el-input>
        </el-form-item>
        <el-form-item label="仓库类型" prop="type">
          <el-select
              v-model="addForm.type"
              placeholder="请选择仓库类型"
          >
            <el-option label="冷冻仓库" value="冷冻仓库"></el-option>
            <el-option label="常温仓库" value="常温仓库"></el-option>
            <el-option label="化学仓库" value="化学仓库"></el-option>
            <el-option label="冷藏仓库" value="冷藏仓库"></el-option>
            <el-option label="恒温仓库" value="恒温仓库"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库面积" prop="area">
          <el-input
              v-model="addForm.area"
              placeholder="请输入仓库面积(平方米)"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改仓库模态框 -->
    <el-dialog
        title="修改仓库"
        :visible.sync="editDialogVisible"
        width="500px"
        :close-on-click-modal="false"
    >
      <el-form
          :model="editForm"
          :rules="rules"
          ref="editFormRef"
          label-width="100px"
      >
        <el-form-item label="仓库ID" prop="wid">
          <el-input v-model="editForm.wid" disabled></el-input>
        </el-form-item>
        <el-form-item label="仓库名称" prop="name">
          <el-input
              v-model="editForm.name"
              placeholder="请输入仓库名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="仓库状态" prop="state">
          <el-select
              v-model="editForm.state"
              placeholder="请选择仓库状态"
          >
            <el-option label="空闲" value="空闲"></el-option>
            <el-option label="使用中" value="使用中"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库位置" prop="location">
          <el-input
              v-model="editForm.location"
              placeholder="请输入仓库位置"
          ></el-input>
        </el-form-item>
        <el-form-item label="仓库类型" prop="type">
          <el-select
              v-model="editForm.type"
              placeholder="请选择仓库类型"
          >
            <el-option label="冷冻仓库" value="冷冻仓库"></el-option>
            <el-option label="常温仓库" value="常温仓库"></el-option>
            <el-option label="化学仓库" value="化学仓库"></el-option>
            <el-option label="冷藏仓库" value="冷藏仓库"></el-option>
            <el-option label="恒温仓库" value="恒温仓库"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库面积" prop="area">
          <el-input
              v-model="editForm.area"
              placeholder="请输入仓库面积(平方米)"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 区域详情对话框 -->
    <el-dialog
        title="仓库区域详情"
        :visible.sync="areaDetailDialogVisible"
        width="1200px"
    >
      <div class="warehouse-detail">
        <div class="detail-header">
          <h3>仓库基本信息</h3>
          <div class="detail-item">
            <span class="detail-label">仓库编号:</span>
            <span class="detail-value">{{ areaDetail.number }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">仓库名称:</span>
            <span class="detail-value">{{ areaDetail.name }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">仓库类型:</span>
            <span class="detail-value">{{ areaDetail.type }}</span>
          </div>
        </div>

        <div class="area-details">
          <h3>区域分布</h3>
          <el-button type="primary" @click="showAddRegionModal" class="action-button">
            <i class="el-icon-plus"></i> 新增区域
          </el-button>
          <el-table
              :data="areaDetail.areas"
              border
              style="width: 100%"
              v-loading="areaLoading"
          >
            <el-table-column prop="r_code" label="区域编号" width="150" align="center"></el-table-column>
            <el-table-column prop="r_name" label="区域名称" width="120" align="center"></el-table-column>
            <el-table-column prop="r_location" label="区域位置" width="180" align="center"></el-table-column>
            <el-table-column prop="a_area" label="区域面积(m²)" width="120" align="center"></el-table-column>
            <el-table-column prop="r_ableuse" label="可用面积(m²)" width="120" align="center"></el-table-column>
            <el-table-column prop="type_name" label="区域类型" width="120" align="center"></el-table-column>
            <el-table-column label="操作" width="330" align="center">
              <template #default="scope">
                <el-button size="mini" @click="handleRegionEdit(scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" @click="handleRegionDelete(scope.row)">删除</el-button>
                <el-button type="primary" @click="handleRegionView(scope.row)" size="mini" class="action-button">
                  <i class="el-icon-view"></i> 查看仓位详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <el-button @click="areaDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑区域模态框 -->
    <el-dialog
        :title="regionModalTitle"
        :visible.sync="regionModalVisible"
        width="600px"
        @close="resetRegionForm"
    >
      <el-form :model="regionForm" :rules="regionRules" ref="regionForm" label-width="100px">
        <el-form-item label="区域id" prop="rid">
          <el-input v-model="regionForm.rid" placeholder="区域id" disabled></el-input>
        </el-form-item>
        <el-form-item label="区域名称" prop="r_name">
          <el-input v-model="regionForm.r_name" placeholder="请输入区域名称"></el-input>
        </el-form-item>
        <el-form-item label="区域位置" prop="r_location">
          <el-input v-model="regionForm.r_location" placeholder="请输入区域位置"></el-input>
        </el-form-item>
        <el-form-item label="区域面积" prop="a_area">
          <el-input v-model="regionForm.a_area"  placeholder="请输入区域面积"></el-input>
        </el-form-item>
        <el-form-item label="区域类型" prop="type_name">
          <el-select v-model="regionForm.type_name" placeholder="请选择区域类型">
            <el-option label="货架" value="1"></el-option>
            <el-option label="钩子" value="2"></el-option>
            <el-option label="平铺" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型数量" prop="r_area_count">
          <el-input v-model="regionForm.r_area_count" placeholder="请输入类型数量"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="regionModalVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRegionForm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 仓位详情对话框 -->
    <el-dialog
        :title="positionDialogTitle"
        :visible.sync="positionDialogVisible"
        width="1070px"
        @close="positionTableData = []"
    >
      <!-- 新增按钮 -->
      <div style="margin-bottom: 15px">
        <el-button type="primary" @click="handleAddPosition">新增仓位</el-button>
      </div>

      <el-table
          :data="positionTableData"
          border
          style="width: 100%"
          v-loading="positionLoading"
          :header-cell-style="{background: '#f5f7fa', color: '#606266'}"
      >
        <el-table-column
            type="index"
            label="序号"
            width="60"
            align="center"
            :index="calculateIndex"
        ></el-table-column>

        <el-table-column
            prop="type.rTypeName"
            label="类型"
            width="150"
            align="center"
        ></el-table-column>

        <el-table-column
            prop="location"
            label="类型位置"
            width="180"
            align="center"
        >
        </el-table-column>

        <el-table-column
            prop="area"
            label="单层/单个面积(m²)"
            width="150"
            align="center"
        ></el-table-column>

        <el-table-column
            prop="space"
            label="可用面积(m²)"
            width="150"
            align="center"
        ></el-table-column>
        <el-table-column
            prop="state"
            label="状态"
            width="130"
            align="center"
            :formatter="formatStatus"
        ></el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template #default="scope">
            <el-button size="mini" @click="handlePositionEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handlePositionDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="positionDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增仓位模态框 -->
    <el-dialog
        title="新增仓位"
        :visible.sync="addPositionVisible"
        width="600px"
    >
      <el-form :model="positionForm" :rules="positionRules" ref="addForm">
        <!-- 区域ID（禁用显示） -->
        <el-form-item label="区域ID" prop="rid">
          <el-input v-model="positionForm.rid" disabled></el-input>
        </el-form-item>

        <el-form-item label="类型位置" prop="location">
          <el-input v-model="positionForm.location" placeholder="请输入类型位置"></el-input>
        </el-form-item>

        <el-form-item label="单层/单个面积(m²)" prop="area">
          <el-input-number v-model="positionForm.area" placeholder="请输入单层/单个面积(平方米)"></el-input-number>
        </el-form-item>

        <el-form-item label="可用面积(m²)" prop="space">
          <el-input-number v-model="positionForm.space" placeholder="请输入可用面积(平方米)"></el-input-number>
        </el-form-item>

        <el-form-item label="状态" prop="state">
          <el-select v-model="positionForm.state" style="width: 100%">
            <el-option
                v-for="item in positionStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="addPositionVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddPosition">确认</el-button>
      </template>
    </el-dialog>

    <!-- 修改仓位模态框 -->
    <el-dialog
        title="修改仓位"
        :visible.sync="editPositionVisible"
        width="600px"
    >
      <el-form :model="positionForm" :rules="positionRules" ref="editForm">
        <el-form-item label="区域ID" prop="rid">
          <el-input v-model="positionForm.rid" disabled></el-input>
        </el-form-item>

        <el-form-item label="类型位置" prop="location">
          <el-input v-model="positionForm.location" ></el-input>
        </el-form-item>

        <el-form-item label="单层/单个面积(m²)" prop="area">
          <el-input-number v-model="positionForm.area" placeholder="请输入单层/单个面积(平方米)"></el-input-number>
        </el-form-item>

        <el-form-item label="可用面积(m²)" prop="space">
          <el-input-number v-model="positionForm.space" placeholder="请输入可用面积(平方米)"></el-input-number>
        </el-form-item>

        <el-form-item label="状态" prop="state">
          <el-select v-model="positionForm.state"
                     style="width: 100%">
            <el-option
                v-for="item in positionStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editPositionVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditPosition">确认</el-button>
      </template>
    </el-dialog>


    <!-- 货物详情模态框 -->
    <el-dialog
        title="仓库货物详情"
        :visible.sync="goodsDetailDialogVisible"
        width="1060px"
    >
      <div class="warehouse-detail">
        <div class="detail-header">
          <h3>仓库基本信息</h3>
          <div class="detail-item">
            <span class="detail-label">仓库编号:</span>
            <span class="detail-value">{{ areaDetail.number }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">仓库名称:</span>
            <span class="detail-value">{{ areaDetail.name }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">仓库类型:</span>
            <span class="detail-value">{{ areaDetail.type }}</span>
          </div>
        </div>

        <div class="area-details">
          <h3>货物列表</h3>
          <el-table
              :data="goodsDetail"
              border
              style="width: 100%"
              v-loading="goodsLoading"
          >
            <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
            <!-- 货物名称 -->
            <el-table-column prop="name" label="货物名称" show-overflow-tooltip width="120" align="center"></el-table-column>
            <!-- 货物类型 -->
            <el-table-column prop="type" label="货物类型" show-overflow-tooltip align="center" width="100"></el-table-column>
            <!-- 单个货物面积 -->
            <el-table-column prop="area" label="单个面积" show-overflow-tooltip align="center" width="100"></el-table-column>
            <!-- 单个货物价值 -->
            <el-table-column prop="money" label="单个价值" show-overflow-tooltip align="center" width="100"></el-table-column>
            <!-- 实际货物数量 -->
            <el-table-column prop="nowNum" label="货物数量" show-overflow-tooltip align="center" width="100"></el-table-column>
            <!-- 货物批次 -->
            <el-table-column prop="code" label="货物批次" show-overflow-tooltip align="center" width="160"></el-table-column>
            <!-- 货物状态 -->
            <el-table-column label="货物状态" prop="state" show-overflow-tooltip align="center" width="100"></el-table-column>
            <!-- 货物存放时长 -->
            <el-table-column prop="time" label="存放时长（天）" show-overflow-tooltip width="120" align="center"></el-table-column>

          </el-table>
        </div>
      </div>
      <template #footer>
        <el-button @click="goodsDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request';

export default {
  data() {
    return {
      tableData: [],
      goodsDetail: [],
      addDialogVisible: false,
      editDialogVisible: false,
      areaDetailDialogVisible: false,
      goodsDetailDialogVisible: false,
      areaLoading: false,
      goodsLoading: false,
      areaDetail: {
        number: '',
        name: '',
        type: '',
        areas: []
      },
      addForm: {
        name: '',
        state: '',
        location: '',
        type: '',
        area: ''
      },
      editForm: {
        wid: '',
        name: '',
        state: '',
        location: '',
        type: '',
        area: ''
      },
      rules: {
        name: [
          {required: true, message: '请输入仓库名称', trigger: 'blur'}
        ],
        state: [
          {required: true, message: '请选择仓库状态', trigger: 'change'}
        ],
        location: [
          {required: true, message: '请输入仓库位置', trigger: 'blur'}
        ],
        type: [
          {required: true, message: '请选择仓库类型', trigger: 'change'}
        ],
        area: [
          {required: true, message: '请输入仓库面积', trigger: 'blur'},
          {pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的数字格式'}
        ]
      },
      searchWareNumber: '',
      searchName: '',
      searchLocation: '',
      searchState: '',
      searchWareType: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,


      // 区域表单相关
      regionModalVisible: false,
      regionModalTitle: '新增区域',
      regionForm: {
        // wname:this.areaDetail.name,
        rid: '',
        r_code: '',
        r_name: '',
        r_location: '',
        a_area: '',
        r_ableuse: '',
        type_name: '',
        r_area_count: 1,
      },
      regionRules: {
        r_code: [{required: true, message: '请输入区域编号', trigger: 'blur'}],
        r_name: [{required: true, message: '请输入区域名称', trigger: 'blur'}],
        r_location: [{required: true, message: '请输入区域位置', trigger: 'blur'}],
        a_area: [{required: true, message: '请输入区域面积', trigger: 'blur'}],
        r_ableuse: [{required: true, message: '请输入可用面积', trigger: 'blur'}],
        type_name: [{required: true, message: '请选择区域类型', trigger: 'change'}]
      },
      currentRegionId: null, // 当前编辑的区域ID

      // 查看仓位详情数据...
      positionDialogVisible: false,
      positionDialogTitle: '仓位详情',
      positionTableData: [], // 仓位列表数据
      positionLoading: false,
      currentRegion: null, // 当前查看的区域
      // 状态选项
      positionStatusOptions: [
        {label: '空闲', value: '0'},
        {label: '使用中', value: '1'},],

      // 仓位表单相关
      // 模态框控制
      addPositionVisible: false,
      editPositionVisible: false,
      deletePositionVisible: false,

      // 表单数据
      positionForm: {
        // rid: this.regionForm.rid,      // 区域ID
        location: '',     // 位置
        area: '',          // 单层/单个面积
        space: '',         // 可用面积
        state: '请选择'        // 状态
      },

      // 当前操作的仓位ID
      currentPositionId: null,
      positionRules: {
        area: [
          {required: true, message: '请输入面积', trigger: 'blur'},
          {type: 'number', min: 0.01, message: '面积必须大于0', trigger: 'blur'}
        ],
        space: [
          {required: true, message: '请输入可用面积', trigger: 'blur'},
          {type: 'number', min: 0, message: '可用面积不能为负数', trigger: 'blur'}
        ],
        state: [
          {required: true, message: '请选择状态', trigger: 'change'}
        ]
      }
    }
  },
  mounted() {
    this.fetchWarehouseList();
  },
  methods: {
    calculateIndex(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },
    handleSearch() {
      this.currentPage = 1;
      this.fetchWarehouseList();
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchWarehouseList();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchWarehouseList();
    },
    fetchWarehouseList() {
      this.loading = true;
      request.get('/warehouse/warehouseList', {
        params: {
          page: this.currentPage,
          size: this.pageSize,
          number: this.searchWareNumber,
          name: this.searchName,
          state: this.searchState,
          location: this.searchLocation,
          type: this.searchWareType,
        }
      })
          .then(response => {
            this.tableData = response.data.data.wareHouseList || [];
            this.total = response.data.data.total || 0;
          })
          .catch(error => {
            console.error('获取仓库列表失败:', error);
            this.$message.error('获取仓库列表失败');
          })
          .finally(() => {
            this.loading = false;
          });
    },

    showAddModal() {
      this.addForm = {
        name: '',
        state: '',
        location: '',
        type: '',
        area: ''
      };
      this.addDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.addForm?.clearValidate();
      });
    },
    handleEdit(row) {
      this.editForm = {
        number: row.number,
        wid: row.wid,
        name: row.name,
        state: row.state,
        location: row.location,
        type: row.type,
        area: row.area
      };
      this.editDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.editFormRef?.clearValidate();
      });
    },
    // 区域详情列表
    handleViewArea(row) {
      this.areaLoading = true;
      this.areaDetailDialogVisible = true;

      // 设置基本信息
      this.areaDetail = {
        wid: row.wid,
        number: row.number,
        name: row.name,
        type: row.type,
        areas: []
      };

      // 获取区域详情
      request.get(`/warehouse/getWarehouseRegionInfoByNumber/${row.number}`)
          .then(response => {
            if (response.data?.data?.warehouseInfos) {
              this.areaDetail.areas = response.data.data.warehouseInfos;
              console.log(response.data.data.warehouseInfos)
            }
          })
          .catch(error => {
            console.error('获取区域详情失败:', error);
            this.$message.error('获取区域详情失败');
          })
          .finally(() => {
            this.areaLoading = false;
          });
    },

    //货物详情列表
    handleViewGoods(row){
      this.goodsLoading=true;
      this.goodsDetailDialogVisible=true;
      // 设置基本信息
      this.areaDetail = {
        wid: row.wid,
        number: row.number,
        name: row.name,
        type: row.type,
        areas: []
      };

      // 获取货物详情
      request.get(`/goods/getGoodsInfo/${row.wid}`)
          .then(response => {
            console.log(response.data)
            console.log(response.data.data.goodsList)
            this.goodsDetail = response.data.data.goodsList;
            this.goodsLoading = false
          })
          .catch(error => {
            console.error('获取区域详情失败:', error);
            this.$message.error('获取区域详情失败');
          })
          .finally(() => {
            this.goodsLoading = false;
          });
    },

    handleDelete(row) {
      this.$confirm('确定要删除该仓库吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.delete(`/warehouse/delWarehouseByNumber/${row.number}`)
            .then(() => {
              this.$message.success('删除成功');
              this.fetchWarehouseList();
            })
            .catch(error => {
              console.error('删除失败:', error);
              this.$message.error('删除失败');
            });
      }).catch(() => {
      });
    },
    submitForm() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          request.post('/warehouse/addWarehouse', this.addForm)
              .then(() => {
                this.$message.success('新增仓库成功');
                this.addDialogVisible = false;
                this.fetchWarehouseList();
              })
              .catch(error => {
                console.error('新增仓库失败:', error);
                this.$message.error(error.response?.data?.message || '新增仓库失败');
              });
        }
      });
    },
    submitEditForm() {
      this.$refs.editFormRef.validate(valid => {
        if (valid) {
          request.put('/warehouse/updateWarehouse', this.editForm)
              .then(() => {
                console.log(this.editForm)
                this.$message.success('修改仓库成功');
                this.editDialogVisible = false;
                this.fetchWarehouseList();
              })
              .catch(error => {
                console.error('修改仓库失败:', error);
                this.$message.error(error.response?.data?.message || '修改仓库失败');
              });
        }
      });
    },
    handleReset() {
      // 清空搜索条件
      this.searchWareNumber = '';
      this.searchName = '';
      this.searchState = ''; // 清空状态筛选（可选：若需要默认选中第一个选项，可设为 '空闲'）
      this.searchLocation = '';
      this.searchWareType = '';

      // 重置分页到第一页
      this.currentPage = 1;

      // 触发重新搜索（清空条件后查询全部数据）
      this.fetchWarehouseList();
    },

    // 以下为区域的新增、编辑、删除
    // 显示新增区域模态框
    showAddRegionModal() {
      this.regionModalTitle = '新增区域'
      this.currentRegionId = '',
          // 重置表单并设置仓库名称
          this.regionForm = {
            rid: '',
            r_code: '',
            r_name: '',
            r_location: '',
            a_area: '',
            r_ableuse: '',
            type_name: '',
            r_area_count: 1,
            wname: this.areaDetail.name // 添加仓库名称
          };
      this.regionModalVisible = true
    },

    // 编辑区域
    handleRegionEdit(row) {
      this.regionModalTitle = '编辑区域'
      this.currentRegionId = row.rid // 假设区域数据有id字段
      this.regionForm = {
        rid: row.rid,
        r_code: row.r_code,
        r_name: row.r_name,
        r_location: row.r_location,
        a_area: row.a_area,
        r_ableuse: row.r_ableuse,
        type_name: row.type_name,
        r_area_count: row.r_area_count || 1,
        wname: this.areaDetail.name,// 添加仓库名称
        wid: this.areaDetail.wid // 添加仓库ID
      }
      this.regionModalVisible = true
    },

    handleRegionDelete(row) {
      this.$confirm('确定要删除该区域吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.delete(`/warehouse/delRegion/${row.rid}`)
            .then(response => {
              if (response.data.success) {  // 检查success字段
                this.$message.success(response.data.errMsg || '删除成功');
                // 重新加载区域列表
                this.handleViewArea({
                  number: this.areaDetail.number,
                  name: this.areaDetail.name,
                  type: this.areaDetail.type
                });
              } else {
                this.$message.warning(response.data.errMsg || '该区域仍有未出库的货物，无法删除');
              }
            })
            .catch(error => {
              console.error('删除失败:', error);
              // 显示服务器返回的错误信息或默认错误信息
              const errorMsg = error.response?.data?.errMsg || '删除失败';
              this.$message.error(errorMsg);
            });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // 提交区域表单
    submitRegionForm() {
      this.$refs.regionForm.validate(valid => {
        if (valid) {
          if (this.currentRegionId) {
            // 编辑现有区域 - 包含仓库ID
            const formData = {
              ...this.regionForm,
              wid: this.areaDetail.wid // 确保包含仓库ID
            };
            // 编辑现有区域
            request.put(`/warehouse/updateRegion`, formData)
                .then(() => {
                  console.log("区域更新信息" + this.regionForm)
                  this.$message.success('区域更新成功')
                  this.regionModalVisible = false
                  // 重新加载区域详情
                  this.handleViewArea({
                    number: this.areaDetail.number,
                    name: this.areaDetail.name,
                    type: this.areaDetail.type
                  });
                }).catch(err => {
              this.$message.error('更新失败: ' + err.message)
            })
          } else {
            // 新增区域 - 确保传递仓库名称
            const formData = {
              ...this.regionForm,
              wname: this.areaDetail.name // 确保包含仓库名称
            };
            // 新增区域
            request.post(`/warehouse/addRegionByWarehouseNumber/`, formData)
                .then(() => {
                  this.$message.success('新增区域成功');
                  this.regionModalVisible = false;
                  // 重新加载区域详情
                  this.handleViewArea({
                    number: this.areaDetail.number,
                    name: this.areaDetail.name,
                    type: this.areaDetail.type
                  });
                })
                .catch(error => {
                  console.error('新增区域失败:', error);
                  this.$message.error('新增区域失败');
                });

          }
        }
      })
    },

    // 重置区域表单
    resetRegionForm() {
      this.$refs.regionForm?.resetFields(),
          this.currentRegionId = null;
      this.regionForm = {
        r_code: '',
        r_name: '',
        r_location: '',
        a_area: '',
        r_ableuse: '',
        type_name: '',
        r_area_count: 1,
        wname: this.areaDetail.name
      }
    },

    // 查看仓位详情列表
    handleRegionView(row) {
      this.currentRegion = row;
      this.positionDialogTitle = `${row.r_name} - 仓位详情`;
      this.positionDialogVisible = true;

      // 获取仓位列表
      request.get(`/warehouse/getPositionList/${row.rid}`)
          .then(response => {
            // if (response.data?.data?.PositionList) {
            console.log("仓位列表"+this.positionTableData)
              this.positionTableData = response.data.data.PositionList;
              console.log(this.positionTableData)
            // }
          })
          .catch(error => {
            console.error('获取区域详情失败:', error);
            this.$message.error('获取区域详情失败');
          })
          .finally(() => {
            this.areaLoading = false;
          });
    },
    // 状态格式化方法
    formatStatus(row) {
      // 根据state值返回对应的文本描述
      return row.state === 0 ? '空闲' : '使用中';
    },

    // 以下是仓位的增加，修改，删除
    // 点击新增按钮
    handleAddPosition() {
      this.addPositionVisible = true;
      this.positionForm = {
        rid: this.currentRegion.rid, // 使用当前查看的区域ID
        location: '',
        area: '',
        space: '',
        state: '0' // 默认状态（0表示空闲）
      };
    },

    // 提交新增仓位
    submitAddPosition() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          // 调用API（确保接口路径正确）
          request.post('/warehouse/addPosition', this.positionForm)
              .then(() => {
                this.$message.success('新增仓位成功');
                this.addPositionVisible = false;
                // 刷新当前区域的仓位列表
                this.handleRegionView(this.currentRegion); // 重新加载仓位数据
              })
              .catch(error => {
                console.error('新增仓位失败:', error);
                // 显示后端返回的具体错误信息
                const errorMsg = error.response?.data?.message || '新增仓位失败';
                this.$message.error(errorMsg);
              });
        }
      });
    },

    //修改仓位
    handlePositionEdit(row){
      this.editPositionVisible = true;
      this.positionForm = {
        id: row.id,
        rid: row.rid,
        location: row.location,
        area: row.area,
        space: row.space,
        state: row.state.toString() // 确保转换为字符串格式
      };
    },

    //提交修改
    submitEditPosition() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          // 构造提交数据（可根据实际需求调整字段）
          const params = {
            id: this.positionForm.id,       // 仓位ID（必传）
            rid: this.positionForm.rid,     // 区域ID
            location: this.positionForm.location,
            area: this.positionForm.area,
            space: this.positionForm.space,
            // state: this.positionForm.state
            state: Number(this.positionForm.state) // 转回数字
          };

          // 调用修改API
          request.put('/warehouse/updatePosition', params)
              .then(() => {
                this.$message.success('修改仓位成功');
                this.editPositionVisible = false;

                // 刷新当前区域的仓位列表
                this.handleRegionView(this.currentRegion);
              })
              .catch(error => {
                console.error('修改仓位失败:', error);
                const errorMsg = error.response?.data?.message || '修改仓位失败';
                this.$message.error(errorMsg);
              });
        }
      });
    },

    handlePositionDelete(row) {
      console.log(row.id)
      this.$confirm('确定要删除该仓位吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 修改这里：使用路径变量而非查询参数
        request.delete(`/warehouse/deletePosition/${row.id}`)
            .then(() => {
              this.$message.success('删除仓位成功');
              this.handleRegionView(this.currentRegion);
            })
              .catch(error => {
                console.error('删除失败:', error);
                // 显示服务器返回的错误信息或默认错误信息
                const errorMsg = error.response?.data?.errMsg || '删除失败';
                this.$message.error(errorMsg);
              });
    }).catch(() => {
  this.$message.info('已取消删除');
});

    },
  }
}
</script>

<style scoped>
.user-management-container {
  padding: 20px;
}

.operation-card {
  margin-bottom: 20px;
}

.operation-area {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.search-area {
  display: flex;
  flex-wrap: nowrap;
  gap: 10px;
  align-items: center;
}

.search-input {
  width: 180px;
}

.search-select {
  width: 180px;
}

.data-card {
  margin-bottom: 20px;
}
.search-button {
  margin-left: 7px;
  transition: all 0.3s;
  border-radius: 4px;
}

/* 重置按钮的样式（与搜索按钮区分） */
.el-button.info {
  background-color: #f4f4f5;
  color: #606266;
  border-color: #dcdfe6;
}

.el-button.info:hover {
  background-color: #e9e9eb;
  color: #4a4c51;
}

.search-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(58, 123, 213, 0.2);
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.action-button {
  margin: 2px;
}

.warehouse-detail {
  padding: 10px;
}

.detail-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.detail-item {
  display: flex;
  margin-bottom: 10px;
}

.detail-label {
  width: 100px;
  font-weight: bold;
  color: #606266;
}

.detail-value {
  flex: 1;
  color: #303133;
}

.area-details {
  margin-top: 20px;
}

h3 {
  margin: 15px 0;
  color: #409EFF;
}

.position-dialog .el-dialog__body {
  padding: 20px;
}

.position-table {
  margin-top: 15px;
}
</style>